const serverPath = "http://127.0.0.1:8080"


function request(jsonFlag,path,method,data){
  var token = wx.getStorageSync('token')
  var header = {
  }
  path  = serverPath + path;
  if(jsonFlag){
    if(token != null && token != undefined){
      header['Authorization'] = token
    }
    return new Promise((resolve,reject)=>{
      wx.request({
        url: path,
        data:data,
        method:method,
        header:header,
        success:res=>{
          if(res.statusCode == 200){
            if(res.data.code == 200){
              resolve(res.data.data)
            }else if(res.data.code == 0){
              wx.showToast({
                title: res.msg,
              })
              reject(res.msg)
            }else if(res.data.code == 401){
              wx.showToast({
                title: "登录过期",
              })
              wx.reLaunch({
                url: '/pages/my/my'
              })
              wx.removeStorageSync('token')
              wx.removeStorageSync('userinfo')
              reject(res.data.msg)
            }else{
              wx.showToast({
                title: "未知异常",
              })
              reject(res.data.data)
            }
          }else{
            wx.showToast({
              title: "请求失败",
            })
            reject(res.data)
          }
        },
        fail:res=>{
          reject(res)
        }
      })
    })
  }
}

wx.$request=request
export default request